package com.barry.pattern.singleton;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 更加优美的Singleton, 线程安全的
 */
public class SingletonCAS {
    /** 利用AtomicReference */
    private static final AtomicReference<SingletonCAS> INSTANCE = new AtomicReference<>();
    /**
     * 私有化
     */
    private SingletonCAS(){
    }
    /**
     * 用CAS确保线程安全
     */
    public static final SingletonCAS getInstance(){
        for (;;) {
            SingletonCAS current = INSTANCE.get();
            if (current != null) {
                return current;
            }
            current = new SingletonCAS();
            if (INSTANCE.compareAndSet(null, current)) {
                return current;
            }
        }
    }

    public static void main(String[] args) {
        SingletonCAS singleton1 = SingletonCAS.getInstance();
        SingletonCAS singleton2 = SingletonCAS.getInstance();
        System.out.println(singleton1 == singleton2);

        SingletonEnum a1 = SingletonEnum.TODAY;
        SingletonEnum b1 = SingletonEnum.TODAY;
        System.out.println(a1 == b1);
    }
}
